<template>
  <view class="page ui-form-basic ui-form-basic_white">
    <page-header :showPlaceHolder="false" :customTitle="customTitle"></page-header>
    <fui-form ref="formRef" :model="form" class="form-wrapper" :top="store.getters.topHeight" labelWidth="120" labelSize="28" labelWeight="bold">
      <fui-form-item label="发货地" arrow prop="startPointStr" left="0" marginTop="14" :padding="['16rpx', 0]" @click="onShowStartPicker">
        <!-- <fui-input :borderBottom="false" :padding="[0]" placeholder="请选择发货地" v-model="form.startPointStr" size="28" disabled></fui-input> -->
        <fui-text :text="form.startPointStr ? form.startPointStr : '请选择发货地'" size="28" :color="form.startPointStr ? '#333' : '#999'"></fui-text>
      </fui-form-item>
      <fui-form-item label="覆盖地" arrow prop="endPointStr" left="0" marginTop="14" :padding="['16rpx', 0]" @click="onShowEndPicker">
        <!-- <fui-input :borderBottom="false" :padding="[0]" placeholder="请选择覆盖地" v-model="form.endPointStr" size="28" disabled></fui-input> -->
        <fui-text :text="form.endPointStr ? form.endPointStr : '请选择覆盖地'" size="28" :color="form.endPointStr ? '#333' : '#999'"></fui-text>
      </fui-form-item>
    </fui-form>
    <view class="btn-wrapper">
      <fui-button class="ui-btn-primary_plain" text="取消" height="78rpx" radius="8rpx" :margin="['0', '54rpx', '0', '0']" @click="cancel"></fui-button>
      <fui-button text="保存" height="78rpx" radius="8rpx" :margin="['0']" :loading="isLoading" :disabled="isLoading" @click="submit"></fui-button>
    </view>

    <!-- 发货地 -->
    <fui-picker layer="4" :options="regionData" :linkage="true" :show="showStartPicker" @change="changeStartPoint" @cancel="showStartPicker = false" :fields='["name","id","children"]'></fui-picker>
    

    <!-- 覆盖地 -->
    <!-- <multilevel-picker ref="endPointPickerRef" :data="regionData" @submit="submitEndPoint"></multilevel-picker> -->
    <multilevel-picker ref="endPointPickerRef" :data="regionData" :cacheData="rangeCacheData" :defaultProps="rangeProps"
    	@submit="submitEndPoint"></multilevel-picker>
  </view>
</template>

<script setup>
import { ref, reactive, inject, computed } from 'vue'
import multilevelPicker from '@/components/multilevel'
import pageHeader from '@/components/header'
import api from "@/api/dispatch.js"
import { onLoad } from '@dcloudio/uni-app';
import systemApi from '@/api/system'
import { useStore } from 'vuex';

const store = useStore();
const modal = inject('$modal')
const tab = inject('$tab')
const supplyId = ref()
const regionData = ref([])

const formRef = ref(null)
const form = reactive({
  id: '',
  startPoint: '',
  startPointStr: '',
  endPoint: '',
  endPointStr: ''
})

const dispatchID = ref()

const customTitle = ref('添加发货地')
onLoad((option) => {
  // getStaffFun(" ")
  if (option.id) {
    dispatchID.value = option.id
    customTitle.value = '编辑发货地'
  }
  if (store.getters.regionData.length) { //运营范围列表
    regionData.value = store.getters.regionData
  } else {
    getRegionData()
  }
  supplyId.value = store.getters.companyId  //供应链/供应商id
  if(option.id){
    getDispatchInfoFun(dispatchID.value)
  }
});

const rules = [
  {
    name: 'startPointStr',
    rule: ['required'],
    msg: ['请选择发货地']
  },
  {
    name: 'endPointStr',
    rule: ['required'],
    msg: ['请选择覆盖地']
  }
]

// 选择发货地
const showStartPicker = ref(false)
// const startPointOptions = regionData.value
const onShowStartPicker = () => {
  showStartPicker.value = true
}
const changeStartPoint = (e) => {
  showStartPicker.value = false
  form.startPoint = JSON.stringify(e || {})
  form.startPointStr = e.result
}

// 选择运营范围
const rangeProps = {
  text: 'name',
  value: 'id',
  children: 'children'
}

//运营范围列表
const getRegionData = () => {
  systemApi.administration().then((res) => {
    if (res.code == 0) {
      regionData.value = res.data
    }
  })
}

// 选择覆盖地
const endPointPickerRef = ref(null)
const onShowEndPicker = () => {
  endPointPickerRef.value.show()
}
const rangeCacheData = ref([])
const submitEndPoint = (res) => {
  form.endPoint = res.value
  form.endPointStr = res.text
  rangeCacheData.value = res.cacheData
}

// 保存
const isLoading = ref(false)
const submit = async () => {
  const submitData = reactive({
    id : dispatchID.value,
    deliveryPlaceCode:form.startPoint,
    deliveryPlace:form.startPointStr,
    coverPlaceCode:form.endPoint,
    coverPlace:form.endPointStr,
    supplyChainId:supplyId.value,
    supplierId:supplyId.value,
  })
  const validRes = await formRef.value.validator(form, rules)
  if (validRes.isPassed) {
    if(dispatchID.value){
      updatetDispatchFun(submitData)
    }else{
      addDispatchFun(submitData)
    }
    isLoading.value = true
  }
  // modal.alert('发货信息保存成功')
}

// 新增
const addApiUrl = computed(() => {
  let apiUrl = ''
  if (store.getters.userType == 1) apiUrl = 'addSupplyDispatch' // 供应链新增
  if (store.getters.userType == 2) apiUrl = 'addSupplierDispatch' // 供应商新增
  return apiUrl
})
// 修改
const updatetApiUrl = computed(() => {
  let apiUrl = ''
  if (store.getters.userType == 1) apiUrl = 'updatetSupplyDispatch' // 供应链修改
  if (store.getters.userType == 2) apiUrl = 'updatetSupplierDispatch' // 供应商修改
  return apiUrl
})

// api 新增
const addDispatchFun = (data) => {
  api[addApiUrl.value](data).then((res) => {
    isLoading.value = false
    if (res.code === 0) {
      modal.msg('添加成功')
      tab.navigateBack()
    } else {
      modal.msgError(res.msg);
    }
  }).catch (err => {
    isLoading.value = false
  });
};
// api 修改
const updatetDispatchFun = (data) => {
  api[updatetApiUrl.value](data).then((res) => {
    isLoading.value = false
    if (res.code === 0) {
      modal.msg('修改成功')
      tab.navigateBack()
    } else {
      modal.msgError(res.msg);
    }
  }).catch (err => {
    isLoading.value = false
  });
};

// api 获取发货地信息
const getDispatchInfoFun = (data) => {
  api.getDispatchInfo(data).then((res) => {
   if (res.code === 0) {
    form.id= res.data.id,
    form.startPoint= res.data.deliveryPlaceCode
    form.startPointStr= res.data.deliveryPlace
    form.endPoint= res.data.coverPlaceCode
    form.endPointStr= res.data.coverPlace
   } else {
     modal.msgError(res.msg);
   }
  });
}; 

const cancel = () => {
  tab.navigateBack()
}


</script>

<style lang="scss" scoped>
@import "@/static/scss/form.scss";
</style>
